<!--博客编写页面-->
<template>
    <div style="width: 819px; margin: 5px auto">
      <div class="card">
        <div style="font-weight: bold; font-size: 24px; margin-bottom: 50px" v-if="!blogId">发表新博客</div>
        <div style="font-weight: bold; font-size: 24px; margin-bottom: 50px" v-else>编辑博客</div>
        <el-form :model="form" label-width="100px" style="padding-right: 50px" :rules="rules" ref="formRef">
          <el-form-item label="标题" prop="title">
            <el-input v-model="form.title" maxlength=50 show-word-limit placeholder="标题"></el-input>
          </el-form-item>
          <el-form-item label="简介" prop="descr">
            <el-input type="textarea" v-model="form.descr"   maxlength=350 show-word-limit  placeholder="简介"></el-input>
          </el-form-item>
          <el-form-item label="封面" prop="cover">
            <el-upload
                :action="$baseUrl + '/files/uploadOSS'"
                :headers="{ token: user.token }"
                list-type="picture"
                :on-success="handleCoverSuccess"
            >
              <el-button type="primary">上传封面</el-button>
            </el-upload>
          </el-form-item>
          <el-form-item label="分类" prop="categoryId">
            <el-select v-model="form.categoryId" style="width: 100%">
              <el-option v-for="item in categoryList" :key="item.id" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="标签" prop="tags">
            <!--    multiple filterable allow-create default-first-option实现下拉框的  自定义创建， 多个标签  功能      -->
            <el-select v-model="tagsArr" multiple filterable allow-create default-first-option style="width: 100%">
              <el-option value="后端"></el-option>
              <el-option value="Java"></el-option>
              <el-option value="面试"></el-option>
              <el-option value="Vue"></el-option>
              <el-option value="前端"></el-option>
              <el-option value="大数据"></el-option>
              <el-option value="算法"></el-option>
              <el-option value="程序员"></el-option>
              <el-option value="小白"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容" prop="content">
            <div id="editor"></div>
          </el-form-item>

        </el-form>
        <div style="text-align: center">
          <el-button type="primary" style="width: 600px;height: 50px; border-radius: 20px" @click="save">发表</el-button>
        </div>
      </div>
    </div>
</template>
<script>
import E from "wangeditor"
import hljs from 'highlight.js'
export default {

  name: "NewBlog",
  data() {
    return {
      form: {},
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      rules: {},
      tagsArr: [],
      categoryList: [],   //博客类型标签汇总
      editor: null,  //富文本数据
      blogId: this.$route.query.blogId

    }
  },
  mounted(){
      this.$request.get('/category/selectAll').then(res => {
        this.categoryList = res.data || []
      })
    this.$request.get('/blog/selectById/'+this.blogId).then(res => {
      this.form = res.data || {}
      if(this.form.id){
        this.tagsArr = JSON.parse(this.form.tags || '[]')
        //异步渲染
        setTimeout( ()=>{
          this.editor.txt.html(this.form.content)
        },0)
      }
    })
    this.setRichText();
  },
//<iframe src= https://www.bilibili.com/video/BV1Cg4y187uN/?spm_id_from=333.337.search-card.all.click&vd_source=e275bb0c659ca5ede33c0026649dc266></iframe>
 methods: {
    //富文本函数（设置富文本）
    setRichText() {
      this.$nextTick(() => {
        this.editor = new E(`#editor`)
        this.editor.highlight = hljs
        this.editor.config.uploadImgServer = this.$baseUrl + '/files/editor/uploadOSS'
        this.editor.config.uploadFileName = 'file'
        this.editor.config.uploadImgHeaders = {
          token: this.user.token
        }
        this.editor.config.uploadImgParams = {
          type: 'img',
        }
        this.editor.config.zIndex = 0
        this.editor.create()  // 创建
      })
    },
    handleCoverSuccess(res) {
      this.form.cover = res.data
    },
    save() {   // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.form.tags = JSON.stringify(this.tagsArr)   //将标签数组以JSON的形式传入数据库中
          this.form.content = this.editor.txt.html()
          if(this.user.role = 'ADMIN'){              //管理员发表博客为官方博客
            this.form.userId = 1
          }else{
            this.form.userId = this.user.id
          }
          this.$request({
            url: this.form.id ? '/blog/update' : '/blog/add',
            method: this.form.id ? 'PUT' : 'POST',
            data: this.form
          }).then(res => {
            if (res.code === '200') {  // 表示成功保存
              this.$message.success('保存成功')
              if(res.data!=null) {
                this.$router.push('/front/blogDetail?blogId='+ res.data.id)
              }else{
                this.$router.push('/front/blogDetail?blogId='+ this.blogId)
              }

            } else {
              this.$message.error(res.msg)  // 弹出错误的信息
            }
          })
        }
      })
    },
  }
}
</script>
<style scoped>

</style>